from Utils.kdeemul import *
from Utils.Settings import *
from Player import *
from Utils.presets import *

_equalizerWindow = None

_offset_owner = None
_offset = 0

class PreampSlider(QSlider):
	def __init__(self,orientation,parent):
		QSlider.__init__(self,orientation,parent)
		QObject.connect(self,SIGNAL("valueChanged(int)"),self.valueChanged)

	def valueChanged(self,value):
		self.emit(PYSIGNAL("preampValueChanged(QSlider *,int)"),(self,-value))
		
	def setPreampValue(self,value):
		self.setValue(-value)
	
	def preampValue(self):
		return -self.value()

class BandSlider(QSlider):
	def __init__(self,orientation,parent,index):
		QSlider.__init__(self,orientation,parent)
		self.index = index
		QObject.connect(self,SIGNAL("valueChanged(int)"),self.valueChanged)
	
	def valueChanged(self,value):
		self.emit(PYSIGNAL("bandValueChanged(QSlider *,int,int)"),(self,self.index,-value))
		
	def setBandValue(self,value):
		self.setValue(-value)
	
	def bandValue(self):
		return -self.value()
		
class LEqualizerWindow(KMainWindow):
	def __init__(self):
		KMainWindow.__init__(self)
		self.setCaption(i18n("Equalizer"))
#		self.buildActions()
#		self.buildMenus()
		self.bandLabels = ['30','60','125','250','500','1K','2K','4K','8K','16K']
		self.settings = LSettings.settings()
		self.buildViews()
		self.restorePosition()
		self.restoreSettings()
		self.adjustSize()
		self.setFixedSize(self.size())

	def restorePosition(self):
		x = self.settings.get('EQ Window X',100)
		y = self.settings.get('EQ Window Y',100)
		self.move(x,y)
	
	def closeEvent(self,ev):
		global _equalizerWindow
		_equalizerWindow = None
		self.settings['EQ Window X'] = self.x()
		self.settings['EQ Window Y'] = self.y()
		QWidget.closeEvent(self,ev)

	def buildViews(self):
		box = QWidget(self)
		hlayout = QHBoxLayout(box)
		vlayout = QVBoxLayout()
		hlayout.addItem(QSpacerItem(20,1,QSizePolicy.Fixed,QSizePolicy.Fixed))
		hlayout.addLayout(vlayout)
		hlayout.addItem(QSpacerItem(20,1,QSizePolicy.Fixed,QSizePolicy.Fixed))
		self.buildUpperView(box,vlayout)
		vlayout.addItem(QSpacerItem(1,20,QSizePolicy.Fixed,QSizePolicy.Fixed))
		self.buildLowerView(box,vlayout)
		self.setCentralWidget(box)

	def buildUpperView(self,container,containerLayout):
		layout = QHBoxLayout()
		containerLayout.addLayout(layout)
		self.buildOnOffCheckbox(container,layout)
		self.buildPresets(container,layout)
	
	def buildOnOffCheckbox(self,container,containerLayout):
		self.onOffItem = QCheckBox(i18n("On"),container)
		QObject.connect(self.onOffItem,SIGNAL("stateChanged(int)"),self.onOffChanged)
		containerLayout.addWidget(self.onOffItem)
	
	def buildPresets(self,container,containerLayout):
		self.presetsItem = KComboBox(False,container)
		for preset in equalizerPresets:
			self.presetsItem.insertItem(preset['Label'])
		QObject.connect(self.presetsItem,SIGNAL("activated(int)"),self.presetsChanged)
		containerLayout.addWidget(self.presetsItem)
	
	def buildLowerView(self,container,containerLayout):
		layout = QHBoxLayout()
		containerLayout.addLayout(layout)
		layout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		#self.buildPreamp(container,layout)
		#layout.addItem(QSpacerItem(20,1,QSizePolicy.Fixed,QSizePolicy.Fixed))
		self.buildEqualizers(container,layout)
		layout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
	
	def buildPreamp(self,container,containerLayout):
		layout = QVBoxLayout()
		containerLayout.addLayout(layout)
		self.preampItem = PreampSlider(Qt.Vertical,container)
		self.preampItem.setRange(-100,100)
		self.preampItem.setTickmarks(QSlider.Right)
		self.preampItem.setTickInterval(25)
		self.preampItem.setMinimumHeight(200)
		QObject.connect(self.preampItem,PYSIGNAL("preampValueChanged(QSlider *,int)"),self.preampChanged)
		layout.addWidget(self.preampItem)
		label = QLabel(i18n('Preamp'),container)
		layout.addWidget(label)
	
	def buildEqualizers(self,container,containerLayout):
		layout = QHBoxLayout()
		containerLayout.addLayout(layout)
		self.bandItems = []
		for i in xrange(0,10):
			self.buildBand(i,container,layout)
			layout.addItem(QSpacerItem(10,1,QSizePolicy.Fixed,QSizePolicy.Fixed))
	
	def buildBand(self,index,container,containerLayout):
		layout = QVBoxLayout()
		containerLayout.addLayout(layout)
		band = BandSlider(Qt.Vertical,container,index)
		band.setRange(-100,100)
		band.setTickmarks(QSlider.Right)
		band.setTickInterval(25)
		band.setMinimumHeight(200)
		QObject.connect(band,PYSIGNAL("bandValueChanged(QSlider *,int,int)"),self.bandChanged)
		self.bandItems.append(band)
		layout.addWidget(band)
		
		label = QLabel(self.bandLabels[index],container)
		layout.addWidget(label)

	def onOffChanged(self,state):
		self.emitEQ()

	def presetsChanged(self,index):
		preset = equalizerPresets[index]
		self.setBands(preset['Bands'])
	
	def getBands(self):
		return map(lambda b:b.bandValue(),self.bandItems)

	def setBands(self,bands):
		for i in xrange(0,10):
			self.bandItems[i].setBandValue(bands[i])
			
	def preampChanged(self,preamp,value):
		self.emitEQ()

	def bandChanged(self,band,index,value):
		#print "band %d changed to %d" %(index,value)
		self.emitEQ()
	
	def emitEQ(self):
		#bands = {'On':self.onOffItem.isOn(),'Bands':map(lambda b:b.bandValue(),self.bandItems),"Preamp":self.preampItem.preampValue()}
		bands = {'On':self.onOffItem.isOn(),'Bands':self.getBands(),"Preamp":0}
		#print bands
		LMusicPlayer.singleton().setEQ(bands)
		self.saveSettings(bands)
	
	def saveSettings(self,bands):
		self.settings['EQ Settings'] = bands
		
	def restoreSettings(self):
		#try:
			bands = self.settings.get('EQ Settings',{'On': False, 'Preamp': 0, 'Bands': [0,0,0,0,0,0,0,0,0,0]})
			self.onOffItem.setOn(bands['On'])
			#self.preampItem.setPreampValue(bands['Preamp'])
			self.setBands(bands['Bands'])
			for preset in equalizerPresets:
				#print "comparing",bands,preset['Bands']
				if bands['Bands']==preset['Bands']:
					self.presetsItem.setCurrentItem(equalizerPresets.index(preset))
					break
		#except: pass

	def static_showEqualizer():
		global _equalizerWindow
		if not _equalizerWindow:
			_equalizerWindow = LEqualizerWindow()
		_equalizerWindow.show()
	showEqualizer = staticmethod(static_showEqualizer)
	
	def static_hideEqualizer():
		global _equalizerWindow
		_equalizerWindow.close()
	hideEqualizer = staticmethod(static_hideEqualizer)
	
	def static_isEqualizerShowing():
		return _equalizerWindow!=None
	isEqualizerShowing = staticmethod(static_isEqualizerShowing)
	
	def static_toggleEqualizer():
		if LEqualizerWindow.isEqualizerShowing():
			LEqualizerWindow.hideEqualizer()
		else:
			LEqualizerWindow.showEqualizer()
	toggleEqualizer = staticmethod(static_toggleEqualizer)
